package cn.bluemobi.app.service.impl;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import cn.bluemobi.app.dto.pay.AlipayDto;
import cn.bluemobi.app.dto.pay.UnionDto;
import cn.bluemobi.app.dto.pay.WechatDto;
import cn.bluemobi.app.entity.form.PayInfoForm;
import cn.bluemobi.app.entity.output.Order;
import cn.bluemobi.app.entity.output.OrderItem;
import cn.bluemobi.app.entity.output.OrderPay;
import cn.bluemobi.app.entity.output.PayInfo;
import cn.bluemobi.app.mapper.MemberMapper;
import cn.bluemobi.app.mapper.PayMapper;
import cn.bluemobi.app.service.PayService;
import cn.bluemobi.app.utils.CommonUtils;
import cn.bluemobi.app.utils.unionPay.UnionPayUtils;
import cn.bluemobi.app.utils.wechatPay.WechatPayUtil;
import cn.bluemobi.common.core.dto.Dto;

/**
 * 
 * @author lvxh
 * 
 */
@Service
@Transactional
public class PayServiceImpl implements PayService {

	@Autowired
	private PayMapper payMapper;

	@Autowired
	private MemberMapper memberMapper;

	@Override
	public Dto<PayInfo> getPayInfo(String memberId, PayInfoForm payInfoForm,
			String remortIP, String type) {
		Dto<PayInfo> dto = new Dto<>();
		AlipayDto alipayDto = null;
		WechatDto wechatDto = null;
		// 批量支付表里插入一条记录
		String batchNo = CommonUtils.currentDate("yyyyMMddHHmmss")
				+ CommonUtils.createNumber(4);
		payInfoForm.setMemberId(memberId);
		payInfoForm.setBatchNo(batchNo);
		if (StringUtils.equals(payInfoForm.getPayType(), "1")) { // 支付宝
			alipayDto = getAlipayDto(remortIP, payInfoForm);
		}
		if (StringUtils.equals(payInfoForm.getPayType(), "2")) { // 微信
			wechatDto = getWechatDto(remortIP, payInfoForm, type);
		}
		PayInfo payInfo = new PayInfo(alipayDto, wechatDto);
		dto.setData(payInfo);
		return dto;
	}

	public AlipayDto getAlipayDto(String remortIP, PayInfoForm payInfoForm) {
		payMapper.insertPayInfo(payInfoForm);
		String total = payInfoForm.getPayMoney().toString();
		AlipayDto pay = new AlipayDto();
		pay.setBatchNo(payInfoForm.getBatchNo());
		pay.setTotal(total);
		return pay;
	}

	public WechatDto getWechatDto(String remortIP, PayInfoForm payInfoForm,
			String type) {
		payMapper.insertPayInfo(payInfoForm);
		// String total = "0.01";
		String total = payInfoForm.getPayMoney();
		Map<String, String> map = new HashMap<>();
		if (StringUtils.equals(type.toLowerCase(), "APP".toLowerCase())) {
			// 调用微信支付接口
			map = WechatPayUtil
					.getOrderPaySn(payInfoForm.getBatchNo(), new DecimalFormat(
							"#").format(Double.parseDouble(total) * 100),
							remortIP);
		}
		return assembly2wechat(map);
	}

	public UnionDto getUnionDto(String remortIP, PayInfoForm payInfoForm) {
		payMapper.insertPayInfo(payInfoForm);
		// 查询金额
		String total = String.valueOf(Double.parseDouble(payInfoForm
				.getPayMoney()) * 0.01);
		// 调用银联接口
		Map<String, String> respData = UnionPayUtils.frontConsume(
				payInfoForm.getBatchNo(), total);
		return assembly2Union(respData);
	}

	private WechatDto assembly2wechat(Map<String, String> map) {
		WechatDto dto = new WechatDto();
		dto.setReturnCode(map.get("return_code"));
		dto.setReturnMsg(map.get("return_msg"));
		dto.setAppid(map.get("appid"));
		dto.setMchId(map.get("mch_id"));
		dto.setDeviceInfo(map.get("device_info"));
		dto.setNonceStr(map.get("nonce_str"));
		dto.setSign(map.get("sign"));
		dto.setResultCode(map.get("result_code"));
		dto.setErrCode(map.get("err_code"));
		dto.setErrCodeDes(map.get("err_code_des"));
		dto.setTradeType(map.get("trade_type"));
		dto.setTotalFee(map.get("total_fee"));
		dto.setPrepayId(map.get("prepay_id"));
		dto.setCodeUrl(map.get("code_url"));
		return dto;
	}

	private UnionDto assembly2Union(Map<String, String> map) {
		UnionDto dto = new UnionDto();
		dto.setVersion(map.get("version"));
		dto.setEncoding(map.get("encoding"));
		dto.setCertId(map.get("certId"));
		dto.setSignMethod(map.get("signMethod"));
		dto.setSignature(map.get("signature"));
		dto.setTxnType(map.get("txnType"));
		dto.setTxnSubType(map.get("txnSubType"));
		dto.setBizType(map.get("bizType"));
		dto.setAccessType(map.get("accessType"));
		dto.setMerId(map.get("merId"));
		dto.setOrderId(map.get("orderId"));
		dto.setTxnTime(map.get("txnTime"));
		dto.setReqReserved(map.get("reqReserved"));
		dto.setRespCode(map.get("respCode"));
		dto.setRespMsg(map.get("respMsg"));
		dto.setTn(map.get("tn"));
		return dto;
	}

	@Override
	public void changePaySuccess(String batchNo, String payType,
			Map<String, String> params) {
		OrderPay orderPay = payMapper.findOrderPayByBatchNo(batchNo);
		if (orderPay != null) {
			if (StringUtils.equals(orderPay.getOperateType(), "0")) {
				List<String> orderNumberList = Arrays.asList(orderPay
						.getOrderNumber().split(","));
				List<Order> orderList = payMapper.findOrders(orderNumberList);
				if (!CollectionUtils.isEmpty(orderList)) {
					for (Order order : orderList) {
						List<OrderItem> orderItems = payMapper
								.findOrderItem(order.getOrderId());
						order.setOrderItems(orderItems);
						// 修改商品订单信息
						Map<String, Object> orderParams = new HashMap<>();
						orderParams.put("orderId", order.getOrderId());
						orderParams.put("payType", payType);
						orderParams.put("payMoney", orderPay.getPayMoney());
						orderParams.put("orderStatus", "1");
						if (!CollectionUtils.isEmpty(params)) {
							if (StringUtils.equals(payType, "1")) {
								orderParams.put("alipayTradeNo",
										params.get("trade_no"));// 支付宝交易号
								orderParams.put("alipayOutTradeNo",
										params.get("out_trade_no"));// 支付单号
							}
							if (StringUtils.equals(payType, "2")) {
								orderParams.put("weixinOutTradeNo",
										params.get("out_trade_no"));// 支付单号
								orderParams.put("weixinTransactionId",
										params.get("transaction_id"));// 微信支付订单号
							}
						}
						System.out.println("==========================修改订单信息："
								+ orderParams.toString());
						payMapper.updateOrder(orderParams);
						// 修改商品销量
						payMapper.updateCommodityBuyCount(orderItems);
						// 修改用户消费金额
						for (OrderItem orderItem : orderItems) {
							// 修改总消费金额
							Double money = Integer.parseInt(orderItem
									.getQuantity())
									* Double.parseDouble(orderItem
											.getSpecificationPrice());
							payMapper.updateMemberTotalConsumeMoney(
									money.toString(), order.getMemberId());
							// 修改商品详情返利积分
							Integer multiple = Integer.parseInt(orderItem
									.getMultiple());
							Double waitRebatePoints = money * multiple;
							payMapper.updateWaitRebatePoints(
									waitRebatePoints.toString(),
									orderItem.getOrderInfoId());
							// 修改用户可返利总消费金额
							payMapper.updateMemberTotalRebateConsumeMoney(
									waitRebatePoints.toString(),
									order.getMemberId());
							if (multiple == 5) {
								// 修改商品是否是专区
								payMapper.updateOrderInfoIsPrefecture("1",
										orderItem.getOrderInfoId());
							}
						}
					}
				}
			}
			if (StringUtils.equals(orderPay.getOperateType(), "1")) {
				payMapper.updateMemberLevel("1", orderPay.getMemberId());
			}
			if (StringUtils.equals(orderPay.getOperateType(), "2")) {
				payMapper.updateMemberLevel("2", orderPay.getMemberId());
			}
			if (StringUtils.equals(orderPay.getOperateType(), "3")) {
				payMapper.updateMemberLevel("3", orderPay.getMemberId());
			}

		}
	}
}
